#coding:utf8

import os
import struct
import math 
import json
import re
pat = re.compile('graph(\d+)\.json')

def toInt(byte):
	return struct.unpack('@I', byte)[0]

def toShort(byte):
	return struct.unpack('@H', byte)[0]	

graphList = []
allGraph = os.listdir('.')
for i in allGraph:
    mat = pat.findall(i)
    if len(mat) > 0:
        graphList.append(int(mat[0]))

print "Graph List is ", graphList



def handle(gid):
    graph = open("graph"+str(gid)+"_extra.binary").read()
    jcon = json.loads(open("graph"+str(gid)+".json").read())

    fn = "playerStart"+str(gid)+".json"
    playerStart ={"playerStart": [0, 0, 0]}
    if os.path.exists(fn):
        print fn
        co = open(fn).read()
        print co
        playerStart = json.loads(co)
 
    unclampedSize = jcon["unclampedSize"]
    
    width = unclampedSize["x"]
    height = unclampedSize["y"]
    print "graphSize", width, height


    length = toInt(graph[:4])
    print "length ", length, length*8+4, len(graph)

    print (len(graph)-4)/length


    #width = int(math.sqrt(length))
    #height = int(width)

    start = 4
    mapdata = []
    mapHeight = []
    readMap = ''
    for i in xrange(0, length):
        pen = toInt(graph[start:start+4])
        start += 4
        flag = toInt(graph[start:start+4])
        start += 4


        x = toInt(graph[start:start+4])
        start+=4
        y = toInt(graph[start:start+4])
        start+=4
        z = toInt(graph[start:start+4])
        start+=4
        
        gridFlags = toShort(graph[start:start+2])
        start+=2
            
        #mapdata.append([x/1000.0, y/1000.0, z/1000.0, flag&0x1])
        mapHeight.append(y/1000.0)
        walk = flag&0x1
        mapdata.append(str(flag&0x1))
        

        if i % width == 0:
            readMap += '\n'
        if width <= 200 or i%width >= width-200:
            if walk == 1:
                readMap += '0'
            else:
                readMap += '1'  	

    '''
    [

    {id:107, width, height, mapData,  changePoint:[
            {id:1,  linkMapId:107,  (目标位置)x:10, y:10, z:20, 
                (进入位置)verfiX:110, verfiY:120, verfiZ:130,
                (当前地图所在Id)mapId:107  
            }
        ]
    }

    ]
    '''

    mapdata = ','.join(mapdata)

    out = {"id":gid, "width":width, "height":height, 
            "center":jcon["center"], 
            "playerStart":playerStart["playerStart"], 
            "mapHeight":mapHeight, "mapdata":mapdata, 'changePoint':[],
    }


    f = open("map"+str(gid)+".txt", 'w')
    f.write(readMap)
    f.close()

    return out

def main():
    aList = []
    for g in graphList:
        res = handle(g)
        aList.append(res)

    wout = json.dumps(aList)
    f = open("MapSourceConfig.xml", 'w')
    f.write(wout)
    f.close()

main()
